package com.example.teesystem.common.utils;

import com.example.teesystem.common.exception.CustomException;
import lombok.Cleanup;
import lombok.experimental.UtilityClass;
import org.apache.xmlbeans.impl.xb.xsdschema.Public;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * @author pxr
 * @data 2022/3/29 11:16
 */

@UtilityClass
public class FileUtil {
    public static final String FILE_PATH = "/file";

    public static final String ISSUE = "/issue/";//题库
    public static final String DATABASE = "/dataBase/";//资料库
    public static final String AVATAR = "/avatar/";//头像
    public static final String COURSE = "/course/";
    public static final String EXAM_FEEDBACK = "/examFeedback/";
    public static final String FILE_PREFIX = "http://42.192.144.66:8080";
    public static final String MCFF = "/mcff/";
    public static final String STU_EXCEL = FILE_PATH+"/publicFile/add_stu.xls";

    public static final String[] SUFFIX = {".jpg",".png",".jpeg",".JPG",".PNG",".JPEG",".mp3",".wav",".mp4"};

    public Response UploadFile(MultipartFile[] files, String filePaths){
        StringBuilder urls = new StringBuilder();
        try {
            if (files.length == 0) {
                return Response.error(ResultCode.FILE_EMPTY.getMsg(), ResultCode.FILE_EMPTY.getCode());
            }
            BufferedOutputStream stream = null;
            for(int i = 0; i < files.length; ++i) {
                MultipartFile file = files[i];
                String filePath = filePaths;
                File dest = new File(filePath);
                if (!dest.exists()) {
                    dest.mkdirs();
                }

                String fileName = file.getOriginalFilename();
                String suffixName = fileName.substring(fileName.lastIndexOf("."));
                boolean contain = false;
                for (String suffix : SUFFIX) {
                    if (suffix.equals(suffixName)) {
                        contain = true;
                        break;
                    }
                }
                if(!contain){
                    throw new CustomException(ResultCode.FILE_ERROR);
                }
                if (file.isEmpty()) {
                    return Response.error(ResultCode.FILE_UPLOAD_ERROR.getMsg(), ResultCode.FILE_UPLOAD_ERROR.getCode());
                }

                try {
                    String url = filePath + TimeUtil.getSecondTimestamp() + "_" + i + suffixName;
                    byte[] bytes = file.getBytes();
                    stream = new BufferedOutputStream(new FileOutputStream(new File(url)));
                    stream.write(bytes);
                    stream.close();
                    urls.append(url).append("$");
                } catch (Exception var12) {
                    System.out.println(var12.getMessage());
                    return Response.error(ResultCode.FILE_UPLOAD_ERROR.getMsg(), ResultCode.FILE_UPLOAD_ERROR.getCode());
                }
            }
        } catch (IllegalStateException var13) {
            System.out.println(var13.getMessage());
            return Response.error(ResultCode.FILE_UPLOAD_ERROR.getMsg(), ResultCode.FILE_UPLOAD_ERROR.getCode());
        }
        urls.deleteCharAt(urls.lastIndexOf("$"));
        Map<String, String> map = new HashMap();
        map.put("url", urls.toString());
        return Response.ok(map);
    }
    
    public Response DownLoadFile(String fileUrl, HttpServletResponse response){
        if (fileUrl != null) {
            File file = new File(fileUrl);
            if (file.exists()) {
                response.addHeader("Content-Disposition", fileUrl);
                byte[] buffer = new byte[1024];
                try(
                        FileInputStream fis = new FileInputStream(file);
                        BufferedInputStream bis = new BufferedInputStream(fis);
                        OutputStream os = response.getOutputStream();
                ) {
                    for(int i = bis.read(buffer); i != -1; i = bis.read(buffer)) {
                        os.write(buffer, 0, i);
                    }
                    return Response.ok();
                } catch (Exception e) {
                    return Response.error(ResultCode.FILE_DOWNLOAD_ERROR.getMsg(), ResultCode.FILE_DOWNLOAD_ERROR.getCode());
                }
            }
        }
        return Response.error(ResultCode.FILE_DOWNLOAD_ERROR.getMsg(), ResultCode.FILE_DOWNLOAD_ERROR.getCode());
    }

    public String CopyFile(String fileUrls, Integer courseId) throws Exception {
        StringBuffer urls = new StringBuffer();

        fileUrls = fileUrls.trim();
        String[] fileUrlArray = fileUrls.split("\\$");

        byte[] buffer = new byte[1024];
        int length;
        int i =0;
        for (String fileUrl : fileUrlArray){
            System.out.println(fileUrl);
            if (fileUrl != null){
                String filePath = FILE_PATH + ISSUE + courseId + "/";
                String suffixName = fileUrl.substring(fileUrl.lastIndexOf("."));
                String url = filePath + TimeUtil.getSecondTimestamp() + "_" + i + suffixName;
                File file = new File(fileUrl);
                File newFile = new File(filePath);
                if (!newFile.exists()){
                    newFile.mkdirs();
                }
                try {
                    @Cleanup
                    InputStream inputStream = new FileInputStream(file); //读入原文件
                    @Cleanup
                    OutputStream outputStream = new FileOutputStream(url);
                    while ((length = inputStream.read(buffer)) != -1){
                        outputStream.write(buffer, 0, length);
                    }
                    urls.append(url).append("$");
                    i++;
                }catch (Exception e){
                    System.out.println(e.getMessage());
                    throw new Exception();
                }
            }
        }
        urls.deleteCharAt(urls.lastIndexOf("$"));
        return urls.toString();
    }

    /**
     * 浏览器以附件形式下载文件
     */
    public static Response downloadFileByWeb(String fileUrl, HttpServletResponse response){
        File file = new File(fileUrl);
        if (file.exists()) {
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;

            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                ServletOutputStream os = response.getOutputStream();
                response.setHeader("Content-disposition", "attachment;filename=" + new String( fileUrl.getBytes("gb2312"), "ISO8859-1" ) );
                response.setCharacterEncoding("utf-8");
                    for(int i = bis.read(buffer); i != -1; i = bis.read(buffer)) {
                        os.write(buffer, 0, i);
                    }
                System.out.println("ok");
                os.flush();
                return Response.ok();
            } catch (Exception var25) {
                System.out.println(var25.getMessage());
                var25.printStackTrace();
                return Response.error(ResultCode.FILE_DOWNLOAD_ERROR.getMsg(), ResultCode.FILE_DOWNLOAD_ERROR.getCode());
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException var24) {
                        System.out.println(var24.getMessage());
                        var24.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException var23) {
                        System.out.println(var23.getMessage());
                        var23.printStackTrace();
                    }
                }

            }
        }
        return Response.error(ResultCode.FILE_DOWNLOAD_ERROR.getMsg(), ResultCode.FILE_DOWNLOAD_ERROR.getCode());
    }

}
